package flashmv.gui;

class ChatBox extends flash.display.Sprite
{

    public var output : flash.display.Sprite;
    public var input : flash.display.Sprite;

    public var outtext : flash.text.TextField;
    public var intext : flash.text.TextField;

    public function new(xsize : Float, ysize : Float, inputysize : Float)
    {
        // add events linking message entry to a PM event
        
        super();
        
        output = new flash.display.Sprite();
        var outg = output.graphics;
        
        input = new flash.display.Sprite();
        var ing = input.graphics;
        
        outg.beginFill(0x222266);
        outg.drawRoundRect(0,0,xsize,ysize-inputysize-1,16,16);
        outg.endFill();

        ing.beginFill(0x4444BB);
        ing.drawRoundRect(0,ysize-inputysize,xsize, inputysize, 16,16);
        ing.endFill();
        
        var chattextformat = new flash.text.TextFormat();
        chattextformat.font = "Bitstream Vera Sans Mono";
        chattextformat.color = 0xFFFFFF;
        chattextformat.size = 20.0;
        
        outtext = new flash.text.TextField();
        outtext.type = flash.text.TextFieldType.DYNAMIC;       
        outtext.embedFonts = true;
        outtext.defaultTextFormat = chattextformat;
        outtext.wordWrap = true;
        outtext.multiline = true;
        
        outtext.width = xsize;
        outtext.height = ysize-inputysize-1;
        
        output.addChild(outtext);
        
        intext = new flash.text.TextField();
        intext.type = flash.text.TextFieldType.INPUT;
        intext.embedFonts = true;
        intext.defaultTextFormat = chattextformat;

        intext.width = xsize;
        intext.height = inputysize-1;
        intext.y = ysize-inputysize;

        intext.text = "";

        input.addChild(intext);
        
        this.addChild(output);
        this.addChild(input);        

        intext.addEventListener(flash.events.KeyboardEvent.KEY_DOWN,
                                this.send);

    }

    public function out(msg : String)
    {
        var startlen = outtext.length;
        outtext.text+=msg+"\n";
        var endlen = outtext.length;
        
        outtext.scrollV+=endlen-startlen;
    }

    public function send(e : flash.events.KeyboardEvent)
    {
        var outstr = "";

        if (e.charCode==13) // "\n"
        {
            if (intext.text.charAt(0)=="/")
            {
                if (intext.text.charAt(1)=="/")
                    outstr = "/say "+intext.text.substr(1);
                else
                    outstr = intext.text;
            }
            else
                outstr = "/say "+intext.text;

            var out = general.GenEvent.extended(outstr);
            FlashClient.sock.writeBytes(out);
            FlashClient.sock.flush();

            intext.text = "";
        }
    }

}